<template>
  <div id="contentBox">
    <div style="text-align:center">
      <el-input v-model="form.questionnaireName" placeholder="请填写问卷名字" />
    </div>
    <div style="text-align:center">
      <el-button type="primary" @click="handleAddQuestions">添加问题</el-button>
    </div>
    <div
      v-for="(item,index) in questionList"
      :key="index"
      class="quslist"
      style="border-bottom:1px solid #666666;padding-bottom:15px;width"
    >
      <div class="everyQus">
        <h3>{{ item.topicName }}</h3>
        <div>
          <i class="el-icon-edit-outline" @click="handleEditQues(item)" />
          <i class="el-icon-delete" @click="handleDelQues(item,index)" />
        </div>
      </div>
      <div
        style="width: 60%;margin: 0px auto;display: flex;flex-direction: column;justify-content: space-between;"
      >
        <el-radio
          v-for="(item1,index1) in item.answers"
          :key="index1"
          :label="item1.answerName"
        >{{ item1.answerName }}</el-radio>
      </div>
    </div>
    <div style="width:60%;margin:0 auto;text-align:center;margin-top:15px">
      <el-button type="primary" @click="createQuestions">保存</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="questionsDialogVisible"
      width="650px"
      @close="$refs['form'].clearValidate()"
      @opened="$refs['form'].clearValidate()"
    >
      <el-form ref="form" :rules="formRules" :model="form" label-width="80px">
        <el-form-item label="问题题目" prop="topicName">
          <el-input v-model="form.topicName" type="textarea" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="问题类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="问题选项">
          <div v-for="(item,index) in answers" :key="index" class="addQusOptions">
            <el-input v-model="item.answerName" maxlength="50" show-word-limit />
            <el-button
              type="success"
              size="mini"
              icon="el-icon-plus"
              circle
              @click="addQusOptins(item,index)"
            />
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-minus"
              circle
              @click="removeQusOptions(item,index)"
            />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">{{ isCreate }}</el-button>
        <!-- <el-button @click="questionsDialogVisible = false">取消</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as Question from '@/api/questions'
export default {
  name: 'QuestionsAdd',
  data() {
    return {
      formRules: {
        type: [{ required: true, message: '请选择问题类型', trigger: 'change' }],
        questionnaireName: [{ required: true, message: '请输入题目', trigger: 'blur' }],
        topicName: [{ required: true, message: '请输入问题题目', trigger: 'blur' }]
      },
      sortNum: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
      questionsDialogVisible: false, // 添加问卷模态框
      title: '添加问题',
      isCreate: '添加',
      orgId: 0,
      id: '', // 题目id
      questId: '', // 问卷id
      form: {
        questionnaireName: '', // 问卷名称
        code: '', // 表示用于模块
        topicName: '', // 题目名称
        topicNumber: '', // 题目序号
        type: '1' // 题目类型（1.单选、2.多选、3.简单题）
      },
      answers: [], // 答案列表
      questionList: [], // 问题+答案列表
      editInfo: {}, // 问卷信息
      editItem: {}, // 问题的信息
      isAddAnswers: false // 开关
    }
  },
  watch: {
    'form.type': {
      handler: function() {
        if (this.form.type === '1') {
          this.answers = [
            { answerNumber: '', answerName: '' },
            { answerNumber: '', answerName: '' }
          ]
        } else if (this.form.type === '2') {
          this.answers.push({ answerNumber: '', answerName: '' })
        }
      }
    }
  },
  mounted() {
    this.getQuestionsList()
  },
  methods: {
    getQuestionsList() {
      Question.questionsDetail({ id: this.$route.query.id }).then((res) => {
        this.form.questionnaireName = res.data.questionnaireName
        this.questionList = res.data.topics
        this.editInfo = res.data
      })
    },
    // 添加问题
    handleAddQuestions() {
      this.title = '添加问题'
      this.questionsDialogVisible = true
      this.form.type = '1'
      this.form.topicName = ''
      this.answers = [
        { answerNumber: '', answerName: '' },
        { answerNumber: '', answerName: '' }
      ]
    },
    // 编辑问题
    handleEditQues(item) {
      this.editItem = item
      this.title = '编辑问题'
      this.isCreate = '保存'
      this.questionsDialogVisible = true
      this.form.topicName = item.topicName
      this.form.type = item.type + ''
      this.id = item.id
      this.questId = item.questId
      this.answers = item.answers
    },
    // 添加问题选项
    addQusOptins(item, index) {
      console.log(this.answers)
      this.answers.push({
        answerNumber: this.sortNum[this.answers.length],
        answerName: '',
        topicId: this.editItem.id
      })
      this.isAddAnswers = true
    },
    // 删除答案
    removeQusOptions(item, index) {
      this.answers.splice(index, 1)
      if (this.answers.length >= 3 && this.form.type === 1) {
        if (item.id) {
          Question.delQuestionsAnswers({ answerId: item.id }).then((res) => {
            if (res.code === '200') {
              this.getQuestionsList()
            }
          })
        }
        return
      }
      if (this.answers.length >= 4 && this.form.type === 2) {
        if (item.id) {
          Question.delQuestionsAnswers({ answerId: item.id }).then((res) => {
            if (res.code === '200') {
              this.getQuestionsList()
            }
          })
        }
        return
      }
    },
    // 删除问题
    handleDelQues(item, index) {
      console.log(item)
      this.$confirm('确定删除此问题？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Question.deleteQuestions({ topicId: item.id }).then((res) => {
          this.questionList.splice(index, 1)
          this.getQuestionsList()
          this.$message.success('删除成功')
        })
      })
    },
    // 提交问卷
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === '编辑问题') {
            if (this.isAddAnswers) {
              // 是否编辑状态下添加问题
              const newAnswers = []
              let isSave = true
              for (const value of this.answers) {
                if (value['id'] === undefined) {
                  newAnswers.push(value)
                }
              }
              for (let i = 0; i < newAnswers.length; i++) {
                if (newAnswers[i]['answerName'] === '') {
                  isSave = false
                  break
                }
              }
              if (isSave) {
                Question.addQuestionsAnswers(newAnswers).then((res) => {
                  if (res.code === '200') {
                    this.isAddAnswers = false
                    this.questionsDialogVisible = false
                    this.getQuestionsList()
                    isSave = true
                  }
                })
              } else {
                this.$message.error('请填写问题项')
              }
              return
            } else {
              // 编辑状态下编辑题目及答案
              this.answers.forEach((item1, index) => {
                item1['answerNumber'] = this.sortNum[index]
                // item1['topicId'] = item1.topicId
                // item1['id'] = item1.id
              })
              const editQuesObj = {
                id: this.id,
                topicName: this.form.topicName,
                topicNumber: '',
                type: +this.form.type,
                answers: this.answers
              }
              Question.editQuestions(editQuesObj).then((res) => {
                if (res.code === '200') {
                  this.$message.success('编辑成功')
                  this.questionsDialogVisible = false
                  this.getQuestionsList()
                }
              })
            }
          } else {
            // 编辑状态下添加问题
            console.log(this.editInfo)
            this.answers.forEach((item, index) => {
              item['answerNumber'] = this.sortNum[index]
            })
            const addQuesObj = {
              questId: this.editInfo.id,
              topicName: this.form.topicName,
              topicNumber: String(this.questionList.length + 1),
              type: +this.form.type,
              answers: this.answers
            }
            Question.addQuestions(addQuesObj).then((res) => {
              console.log(res)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 保存问卷
    createQuestions() {
      if (this.form.questionnaireName.trim() === '') {
        this.$message.error('请填写问卷名字!')
        return
      }
      if (this.questionList.length <= 0) {
        this.$message.error('请创建问卷题目!')
        return
      }
      // let dataObj = {
      //   questionnaireName: this.form.questionnaireName,
      //   orgId: this.orgId,
      //   code: "/user",
      //   topics: [...this.questionList],
      // };
      // Question.addQuestionsList(dataObj).then((res) => {
      //   if (res.code === "200") {
      //     this.$message.success("添加问卷成功!");
      //     this.form.questionnaireName = "";
      //     this.questionList.length = 0;
      //   }
      // });
    },
    handleBack() {
      this.$confirm('此操作将不会保存问卷？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$router.go(-1)
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang='scss' scoped>
#contentBox {
  padding: 10px 20px;
}
.el-input {
  width: 400px;
  margin-bottom: 15px;
}
.el-radio {
  margin-bottom: 10px;
}
.addQusOptions .el-button {
  margin-left: 10px;
}
/deep/ .el-dialog__footer {
  text-align: left;
}
/deep/ .el-dialog__footer {
  padding: 0 30px 30px 30px;
}
.el-form-item__content > .el-input {
  margin-bottom: 0;
}
.quslist {
  width: 100%;
  .everyQus {
    margin: 0 auto;
    width: 60%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    i {
      font-size: 20px;
      margin: 0 5px;
      cursor: pointer;
    }
  }
}
</style>
